package com.lvbaoins.Harmony.quartz.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvbaoins.Harmony.model.exception.ServiceException;
import com.lvbaoins.Harmony.model.exception.TaskException;
import com.lvbaoins.Harmony.quartz.constant.ScheduleConstants;
import com.lvbaoins.Harmony.quartz.domain.SysJob;
import com.lvbaoins.Harmony.quartz.mapper.SysJobMapper;
import com.lvbaoins.Harmony.quartz.util.ScheduleUtils;
import com.lvbaoins.Harmony.sys.core.exception.enums.BizExceptionEnum;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * <p>
 * 定时任务 服务
 * </p>
 *
 * @author gjb
 * @Date 2020-09-15 14:04:23
 */
@Service
public class SysJobService extends ServiceImpl<SysJobMapper, SysJob> {

    @Autowired
    private Scheduler scheduler;

    /**
     * 分页查询
     *
     * @param pageIndex
     * @param limit
     * @param sysJob
     * @return
     */
    public IPage<SysJob> pageList(Integer pageIndex, Integer limit, SysJob sysJob) {
        Page page = new Page<SysJob>(pageIndex, limit);
        QueryWrapper<SysJob> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return this.page(page, queryWrapper);
    }


    /**
     * 新增任务
     *
     * @param sysJob
     * @return
     */
    public int insertJob(SysJob sysJob) throws TaskException, SchedulerException {

        sysJob.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = this.baseMapper.insert(sysJob);
        if (rows > 0) {
            ScheduleUtils.createScheduleJob(scheduler, sysJob);
        }
        return rows;
    }


    /**
     * 立即执行任务
     *
     * @param id
     * @throws SchedulerException
     */
    public void run(Long id) throws SchedulerException {

        SysJob sysJob = this.getById(id);
        if (sysJob == null) {
            throw new ServiceException(BizExceptionEnum.ORDER_NOT_EXISTS);
        }
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, sysJob);
        JobKey jobKey = ScheduleUtils.getJobKey(id, sysJob.getJobGroup());
        scheduler.triggerJob(jobKey, dataMap);
    }

    /**
     * 更新任务
     * @param sysJob
     * @throws SchedulerException
     */
    public void updateJob(SysJob sysJob) throws SchedulerException {
        SysJob oldSysJob = this.getById(sysJob.getId());
        if (oldSysJob == null) {
            throw new ServiceException(BizExceptionEnum.ORDER_NOT_EXISTS);
        }
        boolean b = this.updateById(sysJob);
        if (b) {
            // 判断是否存在
            JobKey jobKey = ScheduleUtils.getJobKey(oldSysJob.getId(), oldSysJob.getJobGroup());
            if (scheduler.checkExists(jobKey)) {
                // 防止创建时存在数据问题 先移除，然后在执行创建操作
                scheduler.deleteJob(jobKey);
            }
            ScheduleUtils.createScheduleJob(scheduler, sysJob);
        }
    }

    /**
     * 删除任务
     * @param jobId
     */
    public void deleteJob(Long jobId) throws SchedulerException {

        SysJob sysJob = this.getById(jobId);
        if (sysJob == null) {
            throw new ServiceException(BizExceptionEnum.ORDER_NOT_EXISTS);
        }
        boolean b = this.removeById(jobId);
        if(b){
            String jobGroup = sysJob.getJobGroup();
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
    }
}
